package org.ocelot.tunes4j.service;

import java.util.List;

import org.ocelot.tunes4j.beans.AudioObject;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;

public class AudioObjectService {

	ObjectContainer session;
	
	public AudioObjectService(){
		openSession();
	} 
	
	public List<AudioObject> load() {
		ObjectSet<AudioObject> result = session.queryByExample(AudioObject.class);
		return (List<AudioObject>) result;
	}
	
	public AudioObject getById(int id) {
		AudioObject proto = new AudioObject();
		proto.setId(id);
		ObjectSet<AudioObject> result = session.queryByExample(proto);
		if(result!=null && result.size()>0)
			return  result.get(0);
		else
			return null;
	}
	
	public void save(AudioObject audioObject) {
		ObjectContainer session = openSession();
		session.store(audioObject);
	}

	public void remove(AudioObject audioObject) {
		ObjectContainer session = openSession();
		session.delete(audioObject);
	}	
	
	public ObjectContainer openSession(){
		if(session==null) {
			session = Db4oEmbedded.openFile(Db4oEmbedded
                .newConfiguration(), "db/audiodb");
		}
		return session;
	}
	
	public void close(){
		if(session!=null) {
			session.close();
			session=null;
		}
	}
	
}
